from rest_framework.decorators import api_view, permission_classes
import datetime
import random
import time

import jwt
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response

from services.models import VisitorAppointmentService
from .models import Company, CompanyEmployeeProfile, User, ParkEmployeeProfile, Visitor

# 创建JWT密钥
JWT_SECRET = getattr(settings, 'JWT_SECRET_KEY', 'smartpark-secret-key')

@api_view(['POST'])
@permission_classes([AllowAny])  # 允许匿名访问登录接口
def login(request):
    """
    用户登录接口 - 支持手机号登录
    """
    # 优先使用phone参数，如果不存在则尝试使用username参数
    phone = request.data.get('phone')
    if not phone:
        # 尝试从username参数获取手机号
        phone = request.data.get('username')
    
    password = request.data.get('password')
    employee_type = None  # 在函数开头初始化
    
    # 验证必填参数
    if not phone:
        return Response({
            'code': 400,
            'message': '请提供手机号'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    if not password:
        return Response({
            'code': 400,
            'message': '请提供密码'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        # 游客模式处理
        if phone == 'guest' and password == 'guest':
            # 生成游客JWT令牌
            guest_id = f'guest_{int(time.time())}'
            payload = {
                'user_id': guest_id,
                'phone': 'guest',
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)  # 游客令牌1天有效
            }
            
            token = jwt.encode(payload, JWT_SECRET, algorithm='HS256')
            
            # 确保token是字符串格式
            if isinstance(token, bytes):
                token = token.decode('utf-8')
            
            # 返回游客模式响应
            return Response({
                'code': 200,
                'message': '游客登录成功',
                'refresh': token,
                'access': token,
                'userId': guest_id,
                'phone': 'guest',
                'userName': '游客',
                'userType': 'guest'
            })
        
        # 通过手机号查询用户
        user = User.objects.get(phone=phone)
        
        # 验证密码
        # 先尝试使用安全的哈希密码验证
        password_correct = check_password(password, user.password)
        
        # 如果哈希验证失败，再尝试明文密码验证（仅用于测试环境）
        if not password_correct and user.password == password:
            password_correct = True
            print(f"警告：用户 {phone} 使用明文密码登录成功")
        
        if password_correct:  # 如果任一验证方式成功
            # 更新最后登录时间 - 使用带时区的datetime
            from django.utils import timezone
            user.last_login_time = timezone.now()
            user.save()
            
            # 生成JWT令牌
            payload = {
                'user_id': user.user_id,
                'phone': user.phone,
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)  # 令牌7天有效
            }
            
            token = jwt.encode(payload, JWT_SECRET, algorithm='HS256')
            
            # 确保token是字符串格式
            if isinstance(token, bytes):
                token = token.decode('utf-8')
            
            # 尝试获取园区员工档案以获取员工类型
            try:
                park_employee_profile = ParkEmployeeProfile.objects.get(user=user)
                employee_type = park_employee_profile.employee_type
            except ParkEmployeeProfile.DoesNotExist:
                # 如果不是园区员工，可以根据业务设置为None或默认值
                pass

            # 返回统一格式的响应
            return Response({
                'code': 200,
                'message': '登录成功',
                'refresh': token,  # 使用同一个token作为refresh和access
                'access': token,
                'userId': user.user_id,
                'phone': user.phone,
                'userName': user.username,  # 添加用户名
                'userType': 'registered',   # 添加用户类型
                'email': user.email,         # 添加邮箱
                'employeeType': employee_type # 添加员工类型
            })
        else:
            return Response({
                'code': 400,
                'message': '密码错误'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    except User.DoesNotExist:
        return Response({
            'code': 404,
            'message': '该手机号未注册'
        }, status=status.HTTP_404_NOT_FOUND)
    
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([AllowAny])  # 允许匿名访问通过手机号登录的接口
def login_by_phone(request):
    """
    通过手机号登录接口
    """
    # 优先使用phone参数，如果不存在则尝试使用username参数
    phone = request.data.get('phone')
    if not phone:
        # 尝试从username参数获取手机号
        phone = request.data.get('username')
        
    password = request.data.get('password')
    
    # 验证必填字段
    if not phone:
        return Response({
            'code': 400,
            'message': '手机号不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)
        
    if not password:
        return Response({
            'code': 400,
            'message': '密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        # 查询用户
        user = User.objects.get(phone=phone)
        
        # 验证密码
        if check_password(password, user.password):  # 使用安全的密码验证方式
            # 更新最后登录时间 - 使用带时区的datetime
            from django.utils import timezone
            user.last_login_time = timezone.now()
            user.save()
            
            # 生成JWT令牌
            refresh_token_payload = {
                'user_id': user.user_id,
                'username': user.username,
                'type': 'refresh',
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)  # 刷新令牌7天有效
            }
            
            access_token_payload = {
                'user_id': user.user_id,
                'username': user.username,
                'type': 'access',
                'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)  # 访问令牌24小时有效
            }
            
            refresh_token = jwt.encode(refresh_token_payload, JWT_SECRET, algorithm='HS256')
            access_token = jwt.encode(access_token_payload, JWT_SECRET, algorithm='HS256')
            
            # 确保token是字符串格式
            if isinstance(refresh_token, bytes):
                refresh_token = refresh_token.decode('utf-8')
            if isinstance(access_token, bytes):
                access_token = access_token.decode('utf-8')
            
            # 返回符合API文档规范的成功响应
            return Response({
                'code': 200,
                'message': '登录成功',
                'refresh': refresh_token,
                'access': access_token,
                'userId': user.user_id,
                'phone': user.phone,
                'userName': user.username,  # 添加用户名
                'userType': 'registered',   # 添加用户类型
                'email': user.email         # 添加邮箱
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'code': 400,
                'message': '密码错误'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    except User.DoesNotExist:
        return Response({
            'code': 404,
            'message': '该手机号未注册'
        }, status=status.HTTP_404_NOT_FOUND)
    
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([AllowAny])  # 允许匿名访问注册接口
def register(request):
    """
    用户注册接口
    """
    try:
        # 获取请求数据
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        profile_type = request.data.get('profile_type', 'company_employee')  # 默认为企业员工
        name = request.data.get('name')
        gender = request.data.get('gender')
        id_card = request.data.get('id_card')
        company_id = request.data.get('company_id')
        
        # 验证必填字段
        if not username or not password or not phone or not name:
            return Response({
                'error': '用户名、密码、手机号和姓名不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 验证手机号格式
        if not phone.isdigit() or len(phone) != 11:
            return Response({
                'error': '手机号格式不正确'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return Response({
                'error': '该用户名已存在'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 检查手机号是否已注册
        if User.objects.filter(phone=phone).exists():
            return Response({
                'error': '该手机号已注册'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 创建新用户
        user = User(
            username=username,
            phone=phone,
            email=email,
            password=make_password(password),  # 加密存储密码
            register_time=datetime.datetime.now(),
            status=1  # 默认激活状态
        )
        user.save()
        
        # 根据profile_type创建相应的档案
        profile_id = None
        
        if profile_type == 'company_employee' and company_id:
            # 验证公司是否存在
            try:
                company = Company.objects.get(company_id=company_id)
                
                # 创建企业员工档案
                from .models import CompanyEmployeeProfile
                profile = CompanyEmployeeProfile(
                    user=user,
                    company=company,
                    name=name,
                    gender=gender,
                    id_card=id_card,
                    is_legal_representative=0,  # 默认非法人代表
                    is_department_manager=0  # 默认非部门经理
                )
                profile.save()
                profile_id = profile.profile_id
                
            except Company.DoesNotExist:
                # 公司不存在，返回错误
                user.delete()  # 回滚用户创建
                return Response({
                    'error': '指定的公司不存在'
                }, status=status.HTTP_400_BAD_REQUEST)
                
        elif profile_type == 'park_employee':
            # 创建园区员工档案

            profile = ParkEmployeeProfile(
                user=user,
                name=name,
                gender=gender,
                id_card=id_card,
                employee_no=f'P{user.user_id:06d}',  # 生成员工编号
                employee_type='普通员工',  # 默认普通员工
                hire_date=datetime.date.today()
            )
            profile.save()
            profile_id = profile.profile_id
        
        # 返回符合API文档规范的成功响应
        return Response({
            'user_id': user.user_id,
            'username': user.username,
            'profile_id': profile_id,
            'message': '用户注册成功'
        }, status=status.HTTP_201_CREATED)
    
    except Exception as e:
        return Response({
            'error': f'注册失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([AllowAny])  # 允许匿名访问游客登录接口
def guest_login(request):
    """
    游客登录接口，无需验证身份
    """
    try:
        # 获取请求数据
        guest_id = request.data.get('guestId', f'guest_{datetime.datetime.now().timestamp()}')
        guest_name = request.data.get('guestName', f'游客{guest_id[-4:]}')
        
        # 生成refresh token，有效期较短（例如1天）
        refresh_token_payload = {
            'guest_id': guest_id,
            'guest_name': guest_name,
            'is_guest': True,
            'type': 'refresh',
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
        }
        
        # 生成access token，有效期更短（例如4小时）
        access_token_payload = {
            'guest_id': guest_id,
            'guest_name': guest_name,
            'is_guest': True,
            'type': 'access',
            'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=4)
        }
        
        refresh_token = jwt.encode(refresh_token_payload, JWT_SECRET, algorithm='HS256')
        access_token = jwt.encode(access_token_payload, JWT_SECRET, algorithm='HS256')
        
        # 确保token是字符串格式
        if isinstance(refresh_token, bytes):
            refresh_token = refresh_token.decode('utf-8')
        if isinstance(access_token, bytes):
            access_token = access_token.decode('utf-8')
        
        # 返回与普通登录一致的格式
        return Response({
            'refresh': refresh_token,
            'access': access_token,
            'guest_info': {
                'guest_id': guest_id,
                'guest_name': guest_name
            }
        }, status=status.HTTP_200_OK)
    
    except Exception as e:
        return Response({
            'error': f'游客登录失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([AllowAny])  # 允许匿名访问刷新接口
def refresh_token(request):
    """
    刷新JWT令牌
    """
    try:
        # 获取请求数据
        old_token = request.data.get('token')
        
        if not old_token:
            return Response({
                'code': 400,
                'message': '缺少token'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 解码token
        try:
            payload = jwt.decode(old_token, JWT_SECRET, algorithms=['HS256'])
            
            # 获取用户信息
            user_id = payload.get('user_id')
            phone = payload.get('phone')
            
            # 生成新的token
            new_payload = {
                'user_id': user_id,
                'phone': phone,
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)
            }
            
            new_token = jwt.encode(new_payload, JWT_SECRET, algorithm='HS256')
            
            # 确保token是字符串格式
            if isinstance(new_token, bytes):
                new_token = new_token.decode('utf-8')
            
            # 返回新的令牌
            return Response({
                'code': 200,
                'message': 'token刷新成功',
                'token': new_token
            })
            
        except jwt.ExpiredSignatureError:
            return Response({
                'code': 401,
                'message': 'token已过期'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except (jwt.InvalidTokenError, jwt.DecodeError):
            return Response({
                'code': 401,
                'message': '无效的token'
            }, status=status.HTTP_401_UNAUTHORIZED)
    
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'刷新token失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
def logout(request):
    """
    用户登出接口
    """
    # 这里不需要做特殊处理，因为JWT是无状态的
    # 客户端只需要删除本地存储的令牌即可
    # 但可以实现黑名单机制，将当前令牌加入黑名单
    
    # 返回成功响应
    return Response({
        'message': '登出成功'
    }, status=status.HTTP_200_OK)

@api_view(['GET'])
def get_current_user(request):
    """
    获取当前登录用户信息
    """
    user = request.user
    
    try:
        # 获取用户类型和姓名
        user_type = 'user'  # 默认为普通用户
        name = user.username
        profile_id = None
        profile_data = {}
        
        # 尝试获取物业员工档案
        try:
            from .models import ParkEmployeeProfile
            employee = ParkEmployeeProfile.objects.get(user=user)
            user_type = 'park_employee'
            name = employee.name
            profile_id = employee.profile_id
            profile_data = {
                'employee_no': employee.employee_no,
                'department': employee.department,
                'employee_type': employee.employee_type,
                'hire_date': employee.hire_date.strftime('%Y-%m-%d') if employee.hire_date else None,
                'gender': employee.gender,  # 添加性别字段
                'address': employee.address  # 添加地址字段
            }
        except Exception as e:
            # 尝试获取企业员工档案
            try:
                from .models import CompanyEmployeeProfile
                employee = CompanyEmployeeProfile.objects.get(user=user)
                user_type = 'company_employee'
                name = employee.name
                profile_id = employee.profile_id
                profile_data = {
                    'company_id': employee.company.company_id,
                    'company_name': employee.company.company_name,
                    'department': employee.department,
                    'position': employee.position,
                    'is_legal_representative': employee.is_legal_representative,
                    'is_department_manager': employee.is_department_manager,
                    'gender': employee.gender  # 添加性别字段
                }
            except Exception as e:
                pass
        
        # 返回符合API规范的响应
        return Response({
            'user_id': user.user_id,
            'username': user.username,
            'name': name,
            'email': user.email,
            'phone': user.phone,
            'avatar_url': user.avatar_url,
            'user_type': user_type,
            'profile_id': profile_id,
            'profile': profile_data
        })
    
    except Exception as e:
        return Response({
            'error': f'获取用户信息失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['PUT'])
def update_profile(request):
    """
    更新当前用户的个人资料
    """
    user = request.user
    
    try:
        # 获取请求数据
        username = request.data.get('username')
        name = request.data.get('name')
        phone = request.data.get('phone')
        email = request.data.get('email')
        gender = request.data.get('gender')
        id_card = request.data.get('id_card')
        address = request.data.get('address')
        department = request.data.get('department')
        position = request.data.get('position')
        
        # 验证手机号格式
        if phone and (not phone.isdigit() or len(phone) != 11):
            return Response({
                'code': 400,
                'message': '手机号格式不正确'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 检查手机号是否已被其他用户使用
        if phone and User.objects.filter(phone=phone).exclude(user_id=user.user_id).exists():
            return Response({
                'code': 400,
                'message': '该手机号已被其他用户使用'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查邮箱是否已被其他用户使用
        if email and User.objects.filter(email=email).exclude(user_id=user.user_id).exists():
            return Response({
                'code': 400,
                'message': '该邮箱已被其他用户使用'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查用户名是否已被其他用户使用
        if username and User.objects.filter(username=username).exclude(user_id=user.user_id).exists():
            return Response({
                'code': 400,
                'message': '该用户名已被其他用户使用'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 更新用户基本信息
        if username:
            user.username = username
        if phone:
            user.phone = phone
        if email:
            user.email = email
        user.save()
        
        # 更新用户详细资料
        profile_updated = False
        park_employee = None
        company_employee = None
        
        # 尝试获取园区员工档案
        try:
            from .models import ParkEmployeeProfile
            park_employee = ParkEmployeeProfile.objects.get(user=user)
        except ParkEmployeeProfile.DoesNotExist:
            pass
            
        # 尝试获取企业员工档案
        try:
            from .models import CompanyEmployeeProfile
            company_employee = CompanyEmployeeProfile.objects.get(user=user)
        except CompanyEmployeeProfile.DoesNotExist:
            pass
            
        # 更新园区员工档案
        if park_employee:
            if name:
                park_employee.name = name
            if gender:
                park_employee.gender = gender
            if id_card:
                park_employee.id_card = id_card
            if department:
                park_employee.department = department
            if address:
                park_employee.address = address
            park_employee.save()
            profile_updated = True
            
        # 更新企业员工档案
        if company_employee:
            if name:
                company_employee.name = name
            if gender:
                company_employee.gender = gender
            if id_card:
                company_employee.id_card = id_card
            if department:
                company_employee.department = department
            if position:
                company_employee.position = position
            company_employee.save()
            profile_updated = True
            
        # 构建响应数据
        response_data = {
            'user_id': user.user_id,
            'username': user.username,
            'phone': user.phone,
            'email': user.email,
            'avatar_url': user.avatar_url,
        }
        
        # 添加详细资料到响应
        if park_employee:
            response_data.update({
                'name': park_employee.name,
                'gender': park_employee.gender,
                'id_card': park_employee.id_card,
                'department': park_employee.department,
                'employee_no': park_employee.employee_no,
                'employee_type': park_employee.employee_type,
                'address': park_employee.address,
            })
        elif company_employee:
            response_data.update({
                'name': company_employee.name,
                'gender': company_employee.gender,
                'id_card': company_employee.id_card,
                'department': company_employee.department,
                'position': company_employee.position,
                'employee_no': company_employee.employee_no,
                'company_id': company_employee.company.company_id,
                'company_name': company_employee.company.company_name,
            })
            
        # 返回成功响应
        return Response({
            'code': 200,
            'message': '个人资料更新成功',
            'data': response_data
        })
    
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'更新个人资料失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保用户已登录
def update_avatar(request):
    """
    更新用户头像
    支持两种方式：
    1. 上传自定义头像文件 - 保存到服务器并返回访问URL
    2. 选择预设头像路径
    """
    user = request.user
    
    try:
        # 检查是否使用预设头像
        preset_avatar = request.data.get('preset_avatar')
        if preset_avatar:
            # 使用预设头像
            # 验证预设头像路径
            if not preset_avatar.startswith('/assets/images/avatar/') or not preset_avatar.endswith('.png'):
                return Response({
                    'code': 400,
                    'message': '无效的预设头像路径'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 提取头像编号
            try:
                avatar_number = int(preset_avatar.split('/')[-1].split('.')[0])
                if avatar_number < 1 or avatar_number > 12:
                    raise ValueError("头像编号超出范围")
            except (ValueError, IndexError):
                return Response({
                    'code': 400,
                    'message': '无效的预设头像路径'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 设置头像URL - 使用前端路径
            avatar_url = preset_avatar
            
            # 更新用户头像URL
            user.avatar_url = avatar_url
            user.save()
            
            # 返回成功响应
            return Response({
                'code': 200,
                'message': '头像更新成功',
                'avatar_url': avatar_url
            })
        
        # 如果不是预设头像，则处理上传的文件
        avatar_file = request.FILES.get('avatar')
        
        if not avatar_file:
            return Response({
                'code': 400,
                'message': '请提供头像文件或选择预设头像'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证文件类型
        allowed_types = ['image/jpeg', 'image/png', 'image/gif']
        if avatar_file.content_type not in allowed_types:
            return Response({
                'code': 400,
                'message': '头像文件格式不支持，请上传JPG/PNG/GIF格式的图片'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证文件大小（限制为2MB）
        if avatar_file.size > 2 * 1024 * 1024:
            return Response({
                'code': 400,
                'message': '头像文件大小不能超过2MB'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 为自定义头像生成一个标识符
        import uuid
        import os
        from django.conf import settings
        
        # 生成唯一标识符
        avatar_id = uuid.uuid4().hex
        
        # 确定文件扩展名
        file_ext = None
        if avatar_file.content_type == 'image/jpeg':
            file_ext = 'jpg'
        elif avatar_file.content_type == 'image/png':
            file_ext = 'png'
        elif avatar_file.content_type == 'image/gif':
            file_ext = 'gif'
        else:
            file_ext = 'jpg'  # 默认扩展名
        
        # 构建头像文件名和保存路径
        avatar_filename = f"avatar_{avatar_id}.{file_ext}"
        
        # 确保avatars目录存在
        avatars_dir = os.path.join(settings.MEDIA_ROOT, 'avatars')
        if not os.path.exists(avatars_dir):
            os.makedirs(avatars_dir)
        
        # 构建完整的文件保存路径
        avatar_filepath = os.path.join(avatars_dir, avatar_filename)
        
        # 保存文件到服务器
        with open(avatar_filepath, 'wb+') as destination:
            for chunk in avatar_file.chunks():
                destination.write(chunk)
        
        # 生成可访问的URL路径
        avatar_url = f"{settings.MEDIA_URL}avatars/{avatar_filename}"
        
        # 更新用户头像URL
        user.avatar_url = avatar_url
        user.save()
        
        # 返回成功响应，包含完整的访问URL
        return Response({
            'code': 200,
            'message': '头像更新成功',
            'avatar_url': avatar_url
        })
    
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'更新头像失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])  # 添加权限豁免
def company_list(request):
    """
    获取企业列表或创建新企业
    GET: 获取企业列表，支持分页和筛选
    POST: 创建新企业
    """
    if request.method == 'GET':
        try:
            # 获取查询参数
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('pageSize', 10))
            name = request.query_params.get('name', '')
            phone = request.query_params.get('phone', '')
            
            # 构建查询条件
            query_filters = {}
            if name:
                query_filters['company_name__icontains'] = name
            if phone:
                query_filters['contact_phone__icontains'] = phone
            
            # 查询数据库
            companies = Company.objects.filter(**query_filters)
            
            # 计算总数
            total = companies.count()
            
            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            companies = companies[start:end]
            
            # 序列化数据
            company_list = []
            for company in companies:
                company_data = {
                    'company_id': company.company_id,
                    'company_type': company.company_type,
                    'company_name': company.company_name,
                    'credit_code': company.credit_code,
                    'contact_phone': company.contact_phone,
                    'entry_date': company.entry_date.strftime('%Y-%m-%d') if company.entry_date else None,
                    'description': company.description,
                    'created_at': company.created_at.strftime('%Y-%m-%d %H:%M:%S') if company.created_at else None,
                    'updated_at': company.updated_at.strftime('%Y-%m-%d %H:%M:%S') if company.updated_at else None
                }
                company_list.append(company_data)
            
            # 返回响应
            response_data = {
                'code': 200,
                'data': {
                    'list': company_list,
                    'total': total
                }
            }
            return Response(response_data)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取企业列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'POST':
        try:
            # 创建新企业
            company_type = request.data.get('company_type')
            company_name = request.data.get('company_name')
            credit_code = request.data.get('credit_code')
            contact_phone = request.data.get('contact_phone')
            entry_date = request.data.get('entry_date')
            description = request.data.get('description', '')
            
            # 验证必填字段
            if not company_type or not company_name or not credit_code:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查公司名称是否已存在
            if Company.objects.filter(company_name=company_name).exists():
                return Response({
                    'code': 400,
                    'message': '公司名称已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查统一社会信用代码是否已存在
            if Company.objects.filter(credit_code=credit_code).exists():
                return Response({
                    'code': 400,
                    'message': '统一社会信用代码已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 设置日期
            entry_date_obj = None
            if entry_date:
                try:
                    entry_date_obj = datetime.datetime.strptime(entry_date, '%Y-%m-%d').date()
                except ValueError:
                    return Response({
                        'code': 400,
                        'message': '入驻日期格式错误，应为YYYY-MM-DD'
                    }, status=status.HTTP_400_BAD_REQUEST)
            else:
                entry_date_obj = datetime.date.today()
            
            # 创建公司记录
            now = datetime.datetime.now()
            company = Company.objects.create(
                company_type=company_type,
                company_name=company_name,
                credit_code=credit_code,
                contact_phone=contact_phone,
                entry_date=entry_date_obj,
                description=description,
                created_at=now,
                updated_at=now
            )
            
            return Response({
                'code': 201,
                'data': {
                    'company_id': company.company_id,
                    'company_name': company.company_name,
                    'message': '公司创建成功'
                }
            }, status=status.HTTP_201_CREATED)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建企业失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])  # 添加权限豁免
def company_detail(request, pk):
    """
    获取、更新或删除指定企业
    GET: 获取企业详情
    PUT: 更新企业信息
    DELETE: 删除企业
    """
    try:
        # 获取企业对象
        company = Company.objects.get(company_id=pk)
    except Company.DoesNotExist:
        return Response({
            'code': 404,
            'message': '企业不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        try:
            # 返回企业详情
            company_data = {
                'company_id': company.company_id,
                'company_type': company.company_type,
                'company_name': company.company_name,
                'credit_code': company.credit_code,
                'contact_phone': company.contact_phone,
                'entry_date': company.entry_date.strftime('%Y-%m-%d') if company.entry_date else None,
                'description': company.description,
                'created_at': company.created_at.strftime('%Y-%m-%dT%H:%M:%SZ') if company.created_at else None,
                'updated_at': company.updated_at.strftime('%Y-%m-%dT%H:%M:%SZ') if company.updated_at else None
            }
            
            return Response({
                'code': 200,
                'data': company_data
            })
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取企业详情失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'PUT':
        try:
            # 更新企业信息
            company_type = request.data.get('company_type')
            company_name = request.data.get('company_name')
            credit_code = request.data.get('credit_code')
            contact_phone = request.data.get('contact_phone')
            entry_date = request.data.get('entry_date')
            description = request.data.get('description', '')
            
            # 验证必填字段
            if not company_type or not company_name or not credit_code:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查公司名称是否已存在（排除自身）
            if Company.objects.filter(company_name=company_name).exclude(company_id=pk).exists():
                return Response({
                    'code': 400,
                    'message': '公司名称已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查统一社会信用代码是否已存在（排除自身）
            if Company.objects.filter(credit_code=credit_code).exclude(company_id=pk).exists():
                return Response({
                    'code': 400,
                    'message': '统一社会信用代码已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 设置日期
            entry_date_obj = None
            if entry_date:
                try:
                    entry_date_obj = datetime.datetime.strptime(entry_date, '%Y-%m-%d').date()
                except ValueError:
                    return Response({
                        'code': 400,
                        'message': '入驻日期格式错误，应为YYYY-MM-DD'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新公司信息
            company.company_type = company_type
            company.company_name = company_name
            company.credit_code = credit_code
            company.contact_phone = contact_phone
            if entry_date_obj:
                company.entry_date = entry_date_obj
            company.description = description
            company.updated_at = datetime.datetime.now()
            company.save()
            
            return Response({
                'code': 200,
                'data': {
                    'company_id': company.company_id,
                    'company_name': company.company_name,
                    'message': '公司信息更新成功'
                }
            })
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'更新企业信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        try:
            # 删除企业
            company.delete()
            
            return Response({
                'code': 204,
                'message': '企业删除成功'
            }, status=status.HTTP_204_NO_CONTENT)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'删除企业失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])  # 添加权限豁免
def employee_list(request):
    """
    获取员工列表或创建新员工
    GET: 获取员工列表，支持分页和筛选
    POST: 创建新员工
    """
    if request.method == 'GET':
        try:
            # 获取查询参数
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('pageSize', 10))
            name = request.query_params.get('name', '')
            company_id = request.query_params.get('companyId', '')
            department = request.query_params.get('department', '')
            company_type = request.query_params.get('companyType', '')  # 新增：按公司类型过滤
            exclude_company_type = request.query_params.get('excludeCompanyType', '')  # 新增：排除特定公司类型
            
            # 构建查询条件
            query_filters = {}
            if name:
                query_filters['name__icontains'] = name
            if company_id:
                query_filters['company_id'] = company_id
            if department:
                query_filters['department__icontains'] = department
            
            # 查询数据库
            from .models import CompanyEmployeeProfile
            employees = CompanyEmployeeProfile.objects.filter(**query_filters)
            
            # 按公司类型过滤
            if company_type:
                employees = employees.filter(company__company_type=company_type)
            if exclude_company_type:
                employees = employees.exclude(company__company_type=exclude_company_type)
            
            # 计算总数
            total = employees.count()
            
            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            employees = employees[start:end]
            
            # 序列化数据
            employee_list = []
            for employee in employees:
                employee_data = {
                    'id': employee.profile_id,
                    'user_id': employee.user.user_id,
                    'name': employee.name,
                    'gender': 1 if employee.gender == 'M' else 2,  # 转换为前端格式：1=男，2=女
                    'company_id': employee.company.company_id,
                    'company_name': employee.company.company_name,
                    'company_type': employee.company.company_type,  # 新增：返回公司类型
                    'department': employee.department,
                    'position': employee.position,
                    'phone': employee.user.phone,
                    'email': employee.user.email,
                    'employee_no': employee.employee_no,
                    'entry_date': employee.created_at.strftime('%Y-%m-%d'),
                    'status': 1,  # 默认在职
                    'created_at': employee.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': employee.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                }
                employee_list.append(employee_data)
            
            # 返回响应
            response_data = {
                'code': 200,
                'data': {
                    'list': employee_list,
                    'total': total
                }
            }
            return Response(response_data)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取员工列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'POST':
        try:
            # 创建新员工
            from .models import User, CompanyEmployeeProfile, Company
            
            # 获取请求数据
            name = request.data.get('name')
            gender = request.data.get('gender')  # 1=男，2=女
            company_id = request.data.get('companyId')
            department = request.data.get('department')
            position = request.data.get('position')
            phone = request.data.get('phone')
            email = request.data.get('email')
            entry_date = request.data.get('entryDate')
            
            # 验证必填字段
            if not name or not gender or not company_id or not department or not position or not phone or not email:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查公司是否存在
            try:
                company = Company.objects.get(company_id=company_id)
            except Company.DoesNotExist:
                return Response({
                    'code': 400,
                    'message': '所选公司不存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建用户账号
            now = datetime.datetime.now()
            user = User.objects.create(
                username=f"{name}_{now.strftime('%Y%m%d%H%M%S')}",  # 生成唯一用户名
                password="123456",  # 默认密码
                phone=phone,
                email=email,
                register_time=now,
                status=1,  # 激活状态
                created_at=now,
                updated_at=now
            )
            
            # 创建员工档案
            gender_code = 'M' if gender == 1 else 'F'
            employee = CompanyEmployeeProfile.objects.create(
                user=user,
                company=company,
                name=name,
                gender=gender_code,
                department=department,
                position=position,
                is_legal_representative=0,  # 默认非法人代表
                is_department_manager=0,  # 默认非部门经理
                created_at=now,
                updated_at=now
            )
            
            return Response({
                'code': 201,
                'data': {
                    'id': employee.profile_id,
                    'name': employee.name,
                    'message': '员工创建成功'
                }
            }, status=status.HTTP_201_CREATED)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建员工失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])  # 添加权限豁免
def employee_detail(request, pk):
    """
    获取、更新或删除指定员工
    GET: 获取员工详情
    PUT: 更新员工信息
    DELETE: 删除员工
    """
    from .models import CompanyEmployeeProfile, Company
    
    try:
        # 获取员工对象
        employee = CompanyEmployeeProfile.objects.get(profile_id=pk)
    except CompanyEmployeeProfile.DoesNotExist:
        return Response({
            'code': 404,
            'message': '员工不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        try:
            # 返回员工详情
            employee_data = {
                'id': employee.profile_id,
                'user_id': employee.user.user_id,
                'name': employee.name,
                'gender': 1 if employee.gender == 'M' else 2,  # 转换为前端格式：1=男，2=女
                'companyId': employee.company.company_id,
                'companyName': employee.company.company_name,
                'department': employee.department,
                'position': employee.position,
                'phone': employee.user.phone,
                'email': employee.user.email,
                'employeeNo': employee.employee_no,
                'entry_date': employee.created_at.strftime('%Y-%m-%d'),
                'status': 1,  # 默认在职
                'remark': '',  # 备注字段，模型中可能没有，这里默认为空
                'created_at': employee.created_at.strftime('%Y-%m-%dT%H:%M:%SZ'),
                'updated_at': employee.updated_at.strftime('%Y-%m-%dT%H:%M:%SZ')
            }
            
            return Response({
                'code': 200,
                'data': employee_data
            })
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取员工详情失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'PUT':
        try:
            # 更新员工信息
            name = request.data.get('name')
            gender = request.data.get('gender')  # 1=男，2=女
            company_id = request.data.get('companyId')
            department = request.data.get('department')
            position = request.data.get('position')
            phone = request.data.get('phone')
            email = request.data.get('email')
            
            # 验证必填字段
            if not name or not gender or not company_id or not department or not position or not phone or not email:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查公司是否存在
            if company_id != employee.company.company_id:
                try:
                    company = Company.objects.get(company_id=company_id)
                    employee.company = company
                except Company.DoesNotExist:
                    return Response({
                        'code': 400,
                        'message': '所选公司不存在'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新用户信息
            user = employee.user
            user.phone = phone
            user.email = email
            user.updated_at = datetime.datetime.now()
            user.save()
            
            # 更新员工信息
            employee.name = name
            employee.gender = 'M' if gender == 1 else 'F'
            employee.department = department
            employee.position = position
            employee.updated_at = datetime.datetime.now()
            employee.save()
            
            return Response({
                'code': 200,
                'data': {
                    'id': employee.profile_id,
                    'name': employee.name,
                    'message': '员工信息更新成功'
                }
            })
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'更新员工信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        try:
            # 删除员工（同时删除关联的用户账号）
            user = employee.user
            employee.delete()
            user.delete()
            
            return Response({
                'code': 204,
                'message': '员工删除成功'
            }, status=status.HTTP_204_NO_CONTENT)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'删除员工失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])  # 添加权限豁免
def company_employees(request, pk):
    """
    获取指定公司的员工列表或为指定公司创建新员工
    GET: 获取指定公司的员工列表
    POST: 为指定公司创建新员工
    """
    
    try:
        # 检查公司是否存在
        company = Company.objects.get(company_id=pk)
    except Company.DoesNotExist:
        return Response({
            'code': 404,
            'message': '公司不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        try:
            # 获取查询参数
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('pageSize', 10))
            name = request.query_params.get('name', '')
            department = request.query_params.get('department', '')
            
            # 构建查询条件
            query_filters = {'company': company}
            if name:
                query_filters['name__icontains'] = name
            if department:
                query_filters['department__icontains'] = department
            
            # 查询数据库
            employees = CompanyEmployeeProfile.objects.filter(**query_filters)
            
            # 计算总数
            total = employees.count()
            
            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            employees = employees[start:end]
            
            # 序列化数据
            employee_list = []
            for employee in employees:
                employee_data = {
                    'id': employee.profile_id,
                    'user_id': employee.user.user_id,
                    'name': employee.name,
                    'gender': 1 if employee.gender == 'M' else 2,
                    'department': employee.department,
                    'position': employee.position,
                    'phone': employee.user.phone,
                    'email': employee.user.email,
                    'employee_no': employee.employee_no,
                    'entry_date': employee.created_at.strftime('%Y-%m-%d'),
                    'status': 1,  # 默认在职
                    'created_at': employee.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': employee.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                }
                employee_list.append(employee_data)
            
            # 返回响应
            response_data = {
                'code': 200,
                'data': {
                    'list': employee_list,
                    'total': total
                }
            }
            return Response(response_data)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取员工列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'POST':
        try:
            # 为指定公司创建新员工
            name = request.data.get('name')
            gender = request.data.get('gender')  # 1=男，2=女
            department = request.data.get('department')
            position = request.data.get('position')
            phone = request.data.get('phone')
            email = request.data.get('email')
            
            # 验证必填字段
            if not name or not gender or not department or not position or not phone or not email:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建用户账号
            now = datetime.datetime.now()
            user = User.objects.create(
                username=f"park_{name}_{now.strftime('%Y%m%d%H%M%S')}",  # 生成唯一用户名
                password="123456",  # 默认密码
                phone=phone,
                email=email,
                register_time=now,
                status=1,  # 激活状态
                created_at=now,
                updated_at=now
            )
            
            # 处理入职日期
            hire_date = now.date()  # 默认为当前日期
            if entry_date:
                try:
                    hire_date = datetime.datetime.strptime(entry_date, '%Y-%m-%d').date()
                except ValueError:
                    return Response({
                        'code': 400,
                        'message': '入职日期格式错误，应为YYYY-MM-DD'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 生成员工编号
            employee_no = f"PK{now.strftime('%y%m%d')}{random.randint(1000, 9999)}"
            
            # 创建员工档案
            gender_code = 'M' if gender == 1 else 'F'
            employee = CompanyEmployeeProfile.objects.create(
                user=user,
                company=company,
                name=name,
                gender=gender_code,
                department=department,
                position=position,
                is_legal_representative=0,  # 默认非法人代表
                is_department_manager=0,  # 默认非部门经理
                created_at=now,
                updated_at=now
            )
            
            return Response({
                'code': 201,
                'data': {
                    'id': employee.profile_id,
                    'name': employee.name,
                    'message': '园区员工创建成功'
                }
            }, status=status.HTTP_201_CREATED)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建园区员工失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])  # 添加权限豁免
def park_employee_list(request):
    """
    获取园区员工列表或创建新园区员工
    GET: 获取园区员工列表，支持分页和筛选
    POST: 创建新园区员工
    """
    if request.method == 'GET':
        try:
            # 获取查询参数
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('pageSize', 10))
            name = request.query_params.get('name', '')
            department = request.query_params.get('department', '')
            employee_type = request.query_params.get('employee_type') # 新增：按员工类型筛选
            
            # 构建查询条件
            query_filters = {}
            if name:
                query_filters['name__icontains'] = name
            if department:
                query_filters['department__icontains'] = department
            if employee_type:
                query_filters['employee_type'] = employee_type

            # 查询数据库
            from .models import ParkEmployeeProfile
            employees = ParkEmployeeProfile.objects.filter(**query_filters).select_related('user')
            
            # 计算总数
            total = employees.count()
            
            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            employees = employees[start:end]
            
            # 序列化数据
            employee_list = []
            for employee in employees:
                employee_data = {
                    'id': employee.profile_id,
                    'user_id': employee.user.user_id,
                    'name': employee.name,
                    'gender': 1 if employee.gender == 'M' else 2,  # 转换为前端格式：1=男，2=女
                    'department': employee.department,
                    'phone': employee.user.phone,
                    'email': employee.user.email,
                    'employee_no': employee.employee_no,
                    'entry_date': employee.created_at.strftime('%Y-%m-%d'),
                    'status': 1,  # 默认在职
                    'created_at': employee.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': employee.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                }
                employee_list.append(employee_data)
            
            # 返回响应
            response_data = {
                'code': 200,
                'data': {
                    'list': employee_list,
                    'total': total
                }
            }
            return Response(response_data)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取园区员工列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'POST':
        try:
            # 创建新园区员工
            from .models import User, ParkEmployeeProfile
            
            # 获取请求数据
            name = request.data.get('name')
            gender = request.data.get('gender')  # 1=男，2=女
            department = request.data.get('department')
            phone = request.data.get('phone')
            email = request.data.get('email')
            entry_date = request.data.get('entryDate')
            
            # 验证必填字段
            if not name or not gender or not department or not phone or not email:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建用户账号
            now = datetime.datetime.now()
            user = User.objects.create(
                username=f"park_{name}_{now.strftime('%Y%m%d%H%M%S')}",  # 生成唯一用户名
                password="123456",  # 默认密码
                phone=phone,
                email=email,
                register_time=now,
                status=1,  # 激活状态
                created_at=now,
                updated_at=now
            )
            
            # 处理入职日期
            hire_date = now.date()  # 默认为当前日期
            if entry_date:
                try:
                    hire_date = datetime.datetime.strptime(entry_date, '%Y-%m-%d').date()
                except ValueError:
                    return Response({
                        'code': 400,
                        'message': '入职日期格式错误，应为YYYY-MM-DD'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 生成员工编号
            employee_no = f"PK{now.strftime('%y%m%d')}{random.randint(1000, 9999)}"
            
            # 创建员工档案
            gender_code = 'M' if gender == 1 else 'F'
            employee = ParkEmployeeProfile.objects.create(
                user=user,
                name=name,
                gender=gender_code,
                employee_no=employee_no,  # 添加员工编号
                department=department,
                employee_type='物业',  # 设置为物业员工类型
                hire_date=hire_date,  # 设置入职日期
                created_at=now,
                updated_at=now
            )
            
            return Response({
                'code': 201,
                'data': {
                    'id': employee.profile_id,
                    'name': employee.name,
                    'message': '园区员工创建成功'
                }
            }, status=status.HTTP_201_CREATED)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建园区员工失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])  # 添加权限豁免
def park_employee_detail(request, pk):
    """
    获取、更新或删除指定园区员工
    GET: 获取园区员工详情
    PUT: 更新园区员工信息
    DELETE: 删除园区员工
    """
    from .models import ParkEmployeeProfile
    
    try:
        # 获取员工对象
        employee = ParkEmployeeProfile.objects.get(profile_id=pk)
    except ParkEmployeeProfile.DoesNotExist:
        return Response({
            'code': 404,
            'message': '园区员工不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        try:
            # 返回员工详情
            employee_data = {
                'id': employee.profile_id,
                'user_id': employee.user.user_id,
                'name': employee.name,
                'gender': 1 if employee.gender == 'M' else 2,  # 转换为前端格式：1=男，2=女
                'department': employee.department,
                'phone': employee.user.phone,
                'email': employee.user.email,
                'employeeNo': employee.employee_no,
                'entryDate': employee.hire_date.strftime('%Y-%m-%d'),
                'status': 1,  # 默认在职
                'remark': '',  # 备注字段，模型中可能没有，这里默认为空
                'created_at': employee.created_at.strftime('%Y-%m-%dT%H:%M:%SZ'),
                'updated_at': employee.updated_at.strftime('%Y-%m-%dT%H:%M:%SZ')
            }
            
            return Response({
                'code': 200,
                'data': employee_data
            })
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取园区员工详情失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'PUT':
        try:
            # 更新员工信息
            name = request.data.get('name')
            gender = request.data.get('gender')  # 1=男，2=女
            department = request.data.get('department')
            phone = request.data.get('phone')
            email = request.data.get('email')
            entry_date = request.data.get('entryDate')
            
            # 验证必填字段
            if not name or not gender or not department or not phone or not email:
                return Response({
                    'code': 400,
                    'message': '缺少必填字段'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新用户信息
            user = employee.user
            user.phone = phone
            user.email = email
            user.updated_at = datetime.datetime.now()
            user.save()
            
            # 处理入职日期
            if entry_date:
                try:
                    hire_date = datetime.datetime.strptime(entry_date, '%Y-%m-%d').date()
                    employee.hire_date = hire_date
                except ValueError:
                    return Response({
                        'code': 400,
                        'message': '入职日期格式错误，应为YYYY-MM-DD'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新员工信息
            employee.name = name
            employee.gender = 'M' if gender == 1 else 'F'
            employee.department = department
            employee.updated_at = datetime.datetime.now()
            employee.save()
            
            return Response({
                'code': 200,
                'data': {
                    'id': employee.profile_id,
                    'name': employee.name,
                    'message': '园区员工信息更新成功'
                }
            })
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'更新园区员工信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        try:
            # 删除员工（同时删除关联的用户账号）
            user = employee.user
            employee.delete()
            user.delete()
            
            return Response({
                'code': 204,
                'message': '园区员工删除成功'
            }, status=status.HTTP_204_NO_CONTENT)
        
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'删除园区员工失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])  # 添加权限豁免
def visitor_list(request):
    """
    获取访客档案列表或创建新访客档案
    GET: 获取访客列表，支持分页和筛选
    POST: 创建新访客
    """
    if request.method == 'GET':
        try:
            # 获取查询参数
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('pageSize', 10))
            name = request.query_params.get('name', '')
            phone = request.query_params.get('phone', '')

            # 构建查询条件
            query_filters = {}
            if name:
                query_filters['name__icontains'] = name
            if phone:
                query_filters['phone__icontains'] = phone

            # 查询数据库
            visitors = Visitor.objects.filter(**query_filters).order_by('-created_at')

            # 计算总数
            total = visitors.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            paged_visitors = visitors[start:end]

            # 序列化数据
            visitor_list_data = []
            for v in paged_visitors:
                visitor_data = {
                    'visitor_id': v.visitor_id,
                    'name': v.name,
                    'gender': v.gender,
                    'id_card': v.id_card,
                    'phone': v.phone,
                    'created_at': v.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': v.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
                }
                visitor_list_data.append(visitor_data)

            # 返回响应
            response_data = {
                'code': 200,
                'data': {
                    'list': visitor_list_data,
                    'total': total
                }
            }
            return Response(response_data)

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取访客档案列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'POST':
        try:
            # 创建新访客档案
            data = request.data
            name = data.get('name')
            phone = data.get('phone')
            id_card = data.get('id_card')

            if not name or not phone:
                return Response({'code': 400, 'message': '姓名和电话是必填项'}, status=status.HTTP_400_BAD_REQUEST)

            if Visitor.objects.filter(phone=phone).exists():
                return Response({'code': 400, 'message': f'电话号码 {phone} 已存在'}, status=status.HTTP_400_BAD_REQUEST)

            if id_card and Visitor.objects.filter(id_card=id_card).exists():
                return Response({'code': 400, 'message': f'身份证号 {id_card} 已存在'}, status=status.HTTP_400_BAD_REQUEST)

            visitor = Visitor.objects.create(
                name=name,
                gender=data.get('gender'),
                id_card=id_card,
                phone=phone
            )

            return Response({
                'code': 201,
                'data': {
                    'visitor_id': visitor.visitor_id,
                    'message': '访客档案创建成功'
                }
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建访客档案失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([AllowAny])  # 添加权限豁免
def visitor_detail(request, pk):
    """
    获取、更新或删除指定访客档案
    GET: 获取访客详情
    PUT: 更新访客信息
    DELETE: 删除访客
    """
    try:
        # 获取访客对象
        visitor = Visitor.objects.get(visitor_id=pk)
    except Visitor.DoesNotExist:
        return Response({
            'code': 404,
            'message': '访客不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        try:
            # 返回访客详情
            visitor_data = {
                'visitor_id': visitor.visitor_id,
                'name': visitor.name,
                'gender': visitor.gender,
                'id_card': visitor.id_card,
                'phone': visitor.phone,
                'created_at': visitor.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': visitor.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
            }

            return Response({
                'code': 200,
                'data': visitor_data
            })

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取访客详情失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'PUT':
        try:
            # 更新访客信息
            data = request.data
            name = data.get('name')
            phone = data.get('phone')
            id_card = data.get('id_card')

            if not name or not phone:
                return Response({'code': 400, 'message': '姓名和电话是必填项'}, status=status.HTTP_400_BAD_REQUEST)

            if Visitor.objects.filter(phone=phone).exclude(visitor_id=pk).exists():
                return Response({'code': 400, 'message': f'电话号码 {phone} 已存在'}, status=status.HTTP_400_BAD_REQUEST)

            if id_card and Visitor.objects.filter(id_card=id_card).exclude(visitor_id=pk).exists():
                return Response({'code': 400, 'message': f'身份证号 {id_card} 已存在'}, status=status.HTTP_400_BAD_REQUEST)

            visitor.name = name
            visitor.phone = phone
            visitor.gender = data.get('gender', visitor.gender)
            visitor.id_card = data.get('id_card', visitor.id_card)
            visitor.save()

            return Response({
                'code': 200,
                'data': {
                    'visitor_id': visitor.visitor_id,
                    'message': '访客信息更新成功'
                }
            })

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'更新访客信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'DELETE':
        try:
            # 检查是否存在关联的预约记录
            if VisitorAppointmentService.objects.filter(visitor=visitor).exists():
                return Response({'code': 400, 'message': '无法删除，该访客存在关联的预约记录'}, status=status.HTTP_400_BAD_REQUEST)

            # 删除访客
            visitor.delete()

            return Response({
                'code': 204,
                'message': '访客删除成功'
            }, status=status.HTTP_204_NO_CONTENT)

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'删除访客失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([AllowAny])
def search_visitors(request):
    """
    搜索访客
    支持按姓名、手机号搜索
    """
    try:
        query = request.query_params.get('query', '')
        
        if not query or len(query) < 1:
            return Response({
                'code': 400,
                'message': '请输入搜索关键词'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 结果列表
        results = []
        
        # 搜索访客
        visitors = Visitor.objects.filter(
            Q(name__icontains=query) | Q(phone__icontains=query)
        ).distinct()[:20]  # 限制结果数量
        
        for visitor in visitors:
            results.append({
                'id': visitor.visitor_id,
                'name': visitor.name,
                'phone': visitor.phone,
                'type': '访客',
                'extra': {
                    'visitor_id': visitor.visitor_id,
                    'id_card': visitor.id_card,
                }
            })
        
        # 结果按名称排序
        results.sort(key=lambda x: x['name'])
        
        return Response({
            'code': 200,
            'message': '搜索成功',
            'data': results
        })
        
    except Exception as e:
        import traceback
        print(traceback.format_exc())
        return Response({
            'code': 500,
            'message': f'搜索访客时发生错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
def search_users(request):
    """
    搜索用户和企业
    支持按用户名、手机号、企业名搜索
    """
    try:
        query = request.query_params.get('query', '')
        
        if not query or len(query) < 2:
            return Response({
                'code': 400,
                'message': '搜索关键词太短，请至少输入2个字符'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 结果列表
        results = []
        
        # 搜索企业
        companies = Company.objects.filter(
            Q(company_name__icontains=query)
        ).distinct()[:20]  # 限制结果数量
        
        for company in companies:
            results.append({
                'id': f'comp_{company.company_id}',
                'name': company.company_name,
                'type': '企业',
                'extra': {
                    'company_id': company.company_id,
                    'contact_phone': company.contact_phone
                }
            })
        
        # 搜索企业员工
        company_employees = CompanyEmployeeProfile.objects.select_related('user', 'company').filter(
            Q(name__icontains=query) |
            Q(user__phone__icontains=query) |
            Q(user__username__icontains=query) |
            Q(company__company_name__icontains=query)
        ).distinct()[:20]
        
        for profile in company_employees:
            user_type = '企业法人' if profile.is_legal_representative == 1 else '企业员工'
            results.append({
                'id': f'user_{profile.user.user_id}',
                'name': profile.name,
                'type': f'{user_type} - {profile.company.company_name}',
                'extra': {
                    'user_id': profile.user.user_id,
                    'username': profile.user.username,
                    'phone': profile.user.phone,
                    'company_id': profile.company.company_id,
                    'department': profile.department,
                    'position': profile.position
                }
            })
        
        # 搜索园区员工
        park_employees = ParkEmployeeProfile.objects.select_related('user').filter(
            Q(name__icontains=query) |
            Q(user__phone__icontains=query) |
            Q(user__username__icontains=query)
        ).distinct()[:20]
        
        for profile in park_employees:
            results.append({
                'id': f'user_{profile.user.user_id}',
                'name': profile.name,
                'type': f'物业员工 - {profile.employee_type}',
                'extra': {
                    'user_id': profile.user.user_id,
                    'username': profile.user.username,
                    'phone': profile.user.phone,
                    'employee_no': profile.employee_no,
                    'department': profile.department
                }
            })
        
        # 搜索普通用户(未关联任何档案的用户)
        other_users = User.objects.filter(
            ~Q(companyemployeeprofile__user_id__isnull=False) &
            ~Q(parkemployeeprofile__user_id__isnull=False) &
            (Q(username__icontains=query) | Q(phone__icontains=query))
        ).distinct()[:20]
        
        for user in other_users:
            results.append({
                'id': f'user_{user.user_id}',
                'name': user.username,
                'type': '个人租户',
                'extra': {
                    'user_id': user.user_id,
                    'phone': user.phone,
                    'email': user.email
                }
            })
        
        # 结果按名称排序
        results.sort(key=lambda x: x['name'])
        
        return Response({
            'code': 200,
            'message': '搜索成功',
            'data': results
        })
        
    except Exception as e:
        import traceback
        print(traceback.format_exc())
        return Response({
            'code': 500,
            'message': f'搜索用户时发生错误: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# Dashboard统计接口
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def employee_count(request):
    """获取园区员工数量"""
    # 使用ParkEmployeeProfile关联查询替代user_type字段
    count = ParkEmployeeProfile.objects.count()
    return Response({'count': count})

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def company_employee_count(request):
    """获取企业员工数量"""
    # 使用CompanyEmployeeProfile关联查询替代user_type字段
    count = CompanyEmployeeProfile.objects.count()
    return Response({'count': count})

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def visitor_count(request):
    """获取访客数量"""
    # 使用Visitor模型查询替代user_type字段
    count = Visitor.objects.count()
    return Response({'count': count})

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request):
    """
    修改用户密码
    """
    user = request.user
    old_password = request.data.get('oldPassword')
    new_password = request.data.get('newPassword')
    
    # 验证必填字段
    if not old_password or not new_password:
        return Response({
            'code': 400,
            'message': '旧密码和新密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证旧密码是否正确
    password_correct = check_password(old_password, user.password)
    
    # 如果哈希验证失败，再尝试明文密码验证
    if not password_correct and user.password == old_password:
        password_correct = True
    
    if not password_correct:
        return Response({
            'code': 400,
            'message': '旧密码不正确'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 更新密码
    user.password = make_password(new_password)
    user.updated_at = datetime.datetime.now()
    user.save()
    
    return Response({
        'code': 200,
        'message': '密码修改成功'
    })

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_user_work_orders(request):
    """
    获取用户相关的工单列表
    支持按工单类型和日期范围筛选
    """
    user = request.user
    
    # 获取查询参数
    page = int(request.query_params.get('page', 1))
    page_size = int(request.query_params.get('pageSize', 10))
    order_type = request.query_params.get('type', '')
    start_date = request.query_params.get('startDate')
    end_date = request.query_params.get('endDate')
    priority = request.query_params.get('priority', '')  # 添加优先级筛选
    
    # 构建日期过滤条件
    date_filters = {}
    if start_date:
        date_filters['application_time__gte'] = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    if end_date:
        # 添加一天以包含整个结束日期
        end_date_obj = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        end_date_obj = end_date_obj + datetime.timedelta(days=1)
        date_filters['application_time__lt'] = end_date_obj
    
    # 根据用户角色和工单类型获取不同类型的工单
    from services.models import RepairService, CleaningBookingService, WaterDeliveryService
    from services.views import determine_task_priority  # 导入优先级判断函数
    
    # 优先级中英文映射
    priority_map = {
        'high': '高',
        'medium': '中',
        'low': '低'
    }
    
    # 初始化结果列表和总数
    work_orders = []
    total_count = 0
    
    # 查询维修工单
    if not order_type or order_type == 'repair':
        try:
            # 查询条件：用户是申请人或处理人
            # 获取维修工单
            repair_orders = RepairService.objects.select_related(
                'unit__building', 'unit__floor', 'device'
            ).filter(
                Q(applicant_user_id=user.user_id) | Q(handler_user_id=user.user_id),
                **date_filters
            ).order_by('-application_time')
            
            # 添加到结果列表
            for order in repair_orders:
                # 计算优先级
                task_priority = determine_task_priority(order)
                # 转换为中文优先级
                priority_text = priority_map.get(task_priority, '低')
                
                # 如果有优先级筛选，跳过不匹配的工单
                if priority and priority_text != priority:
                    continue
                
                # 获取地点信息
                location = ""
                if order.unit:
                    location = f"{order.unit.building.name} {order.unit.floor.actual_label} {order.unit.unit_number}"
                elif order.device:
                    if order.device.unit:
                        location = f"{order.device.unit.building.name} {order.device.unit.floor.actual_label} {order.device.unit.unit_number}"
                    else:
                        location = f"{order.device.building.name} {order.device.location_desc if order.device.location_desc else ''}"
                
                work_orders.append({
                    'id': f'R{order.repair_id}',
                    'title': f'维修工单 - {order.fault_description[:20]}{"..." if len(order.fault_description) > 20 else ""}',
                    'type': 'repair',
                    'status': order.status,
                    'priority': priority_text,  # 添加优先级字段
                    'location': location,
                    'createTime': order.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'completeTime': order.completion_time.strftime('%Y-%m-%d %H:%M:%S') if order.completion_time else None
                })
        except Exception as e:
            print(f"获取维修工单错误: {str(e)}")
    
    # 查询保洁工单
    if not order_type or order_type == 'cleaning':
        try:
            # 获取保洁工单
            cleaning_orders = CleaningBookingService.objects.select_related(
                'unit__building', 'unit__floor'
            ).filter(
                Q(applicant_user_id=user.user_id) | Q(handler_user_id=user.user_id),
                **date_filters
            ).order_by('-application_time')
            
            # 添加到结果列表
            for order in cleaning_orders:
                # 计算优先级
                task_priority = determine_task_priority(order)
                # 转换为中文优先级
                priority_text = priority_map.get(task_priority, '低')
                
                # 如果有优先级筛选，跳过不匹配的工单
                if priority and priority_text != priority:
                    continue
                
                # 获取地点信息
                location = ""
                if order.unit:
                    location = f"{order.unit.building.name} {order.unit.floor.actual_label} {order.unit.unit_number}"
                
                work_orders.append({
                    'id': f'C{order.booking_id}',
                    'title': f'保洁工单 - {order.unit.unit_number if hasattr(order, "unit") and order.unit else "未指定单元"}',
                    'type': 'cleaning',
                    'status': order.status,
                    'priority': priority_text,  # 添加优先级字段
                    'location': location,
                    'createTime': order.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'completeTime': order.completion_time.strftime('%Y-%m-%d %H:%M:%S') if order.completion_time else None
                })
        except Exception as e:
            print(f"获取保洁工单错误: {str(e)}")
    
    # 查询送水工单
    if not order_type or order_type == 'water':
        try:
            # 获取送水工单
            water_orders = WaterDeliveryService.objects.select_related(
                'unit__building', 'unit__floor'
            ).filter(
                Q(applicant_user_id=user.user_id) | Q(deliverer_user_id=user.user_id),
                **date_filters
            ).order_by('-application_time')
            
            # 添加到结果列表
            for order in water_orders:
                # 计算优先级
                task_priority = determine_task_priority(order)
                # 转换为中文优先级
                priority_text = priority_map.get(task_priority, '低')
                
                # 如果有优先级筛选，跳过不匹配的工单
                if priority and priority_text != priority:
                    continue
                
                # 获取地点信息
                location = order.delivery_address
                if order.unit:
                    location = f"{order.unit.building.name} {order.unit.floor.actual_label} {order.unit.unit_number}"
                
                work_orders.append({
                    'id': f'W{order.service_id}',
                    'title': f'送水工单 - {order.product_name} x{order.quantity}',
                    'type': 'water',
                    'status': order.status,
                    'priority': priority_text,  # 添加优先级字段
                    'location': location,
                    'createTime': order.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'completeTime': order.actual_delivery_time.strftime('%Y-%m-%d %H:%M:%S') if order.actual_delivery_time else None
                })
        except Exception as e:
            print(f"获取送水工单错误: {str(e)}")
    
    # 按创建时间排序
    work_orders.sort(key=lambda x: x['createTime'], reverse=True)
    total_count = len(work_orders)
    
    # 分页
    start = (page - 1) * page_size
    end = start + page_size
    paged_orders = work_orders[start:end] if start < len(work_orders) else []
    
    # 返回响应
    return Response({
        'code': 200,
        'data': {
            'list': paged_orders,
            'total': total_count
        }
    })

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_user_profile(request):
    """
    获取当前用户的个人资料
    """
    user = request.user
    
    try:
        # 构建基本响应数据
        response_data = {
            'user_id': user.user_id,
            'username': user.username,
            'phone': user.phone,
            'email': user.email,
            'avatar_url': user.avatar_url,
            'register_time': user.register_time,
            'last_login_time': user.last_login_time
        }
        
        # 尝试获取园区员工档案
        try:
            from .models import ParkEmployeeProfile
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            response_data.update({
                'profile_type': 'park_employee',
                'name': park_employee.name,
                'gender': park_employee.gender,
                'id_card': park_employee.id_card,
                'department': park_employee.department,
                'employee_no': park_employee.employee_no,
                'employee_type': park_employee.employee_type,
                'address': park_employee.address,
                'hire_date': park_employee.hire_date
            })
        except ParkEmployeeProfile.DoesNotExist:
            pass
            
        # 尝试获取企业员工档案
        try:
            from .models import CompanyEmployeeProfile
            company_employee = CompanyEmployeeProfile.objects.get(user=user)
            response_data.update({
                'profile_type': 'company_employee',
                'name': company_employee.name,
                'gender': company_employee.gender,
                'id_card': company_employee.id_card,
                'department': company_employee.department,
                'position': company_employee.position,
                'employee_no': company_employee.employee_no,
                'company_id': company_employee.company.company_id,
                'company_name': company_employee.company.company_name,
                'is_legal_representative': company_employee.is_legal_representative,
                'is_department_manager': company_employee.is_department_manager
            })
        except CompanyEmployeeProfile.DoesNotExist:
            pass
            
        return Response({
            'code': 200,
            'message': '获取个人资料成功',
            'data': response_data
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取个人资料失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_password(request):
    """
    更新用户密码
    """
    user = request.user
    old_password = request.data.get('oldPassword')
    new_password = request.data.get('newPassword')
    confirm_password = request.data.get('confirmPassword')
    
    # 验证必填字段
    if not old_password or not new_password or not confirm_password:
        return Response({
            'code': 400,
            'message': '旧密码、新密码和确认密码不能为空'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证新密码和确认密码是否一致
    if new_password != confirm_password:
        return Response({
            'code': 400,
            'message': '新密码和确认密码不一致'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证新密码长度
    if len(new_password) < 6:
        return Response({
            'code': 400,
            'message': '新密码长度不能少于6个字符'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证旧密码是否正确
    from django.contrib.auth.hashers import check_password, make_password
    password_correct = check_password(old_password, user.password)
    
    # 如果哈希验证失败，再尝试明文密码验证
    if not password_correct and user.password == old_password:
        password_correct = True
    
    if not password_correct:
        return Response({
            'code': 400,
            'message': '旧密码不正确'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 更新密码
    user.password = make_password(new_password)
    user.save()
    
    return Response({
        'code': 200,
        'message': '密码修改成功'
    })

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_employee_profile(request):
    """
    获取当前用户的企业员工信息
    """
    try:
        user = request.user
        
        # 尝试获取用户的企业员工档案
        try:
            employee_profile = CompanyEmployeeProfile.objects.get(user_id=user.user_id)
            
            # 获取所属企业信息
            company = Company.objects.get(company_id=employee_profile.company_id)
            
            # 构建响应数据
            profile_data = {
                'profile_id': employee_profile.profile_id,
                'name': employee_profile.name,
                'gender': employee_profile.gender,
                'id_card': employee_profile.id_card,
                'employee_no': employee_profile.employee_no,
                'department': employee_profile.department,
                'position': employee_profile.position,
                'is_legal_representative': employee_profile.is_legal_representative,
                'is_department_manager': employee_profile.is_department_manager,
                'company_id': employee_profile.company_id,
                'company_name': company.company_name
            }
            
            return Response({
                'code': 200,
                'message': '获取员工信息成功',
                'data': profile_data
            })
            
        except CompanyEmployeeProfile.DoesNotExist:
            # 用户没有关联的企业员工档案
            return Response({
                'code': 404,
                'message': '未找到企业员工信息',
                'data': None
            }, status=status.HTTP_404_NOT_FOUND)
            
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取企业员工信息失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_employee_profile(request):
    """
    更新或创建企业员工信息
    """
    try:
        user = request.user
        data = request.data
        
        # 验证公司ID
        company_id = data.get('company_id')
        if company_id:
            try:
                company = Company.objects.get(company_id=company_id)
            except Company.DoesNotExist:
                return Response({
                    'code': 400,
                    'message': '公司不存在'
                }, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({
                'code': 400,
                'message': '请提供公司ID'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查必填字段
        required_fields = ['name']
        for field in required_fields:
            if not data.get(field):
                return Response({
                    'code': 400,
                    'message': f'缺少必填字段: {field}'
                }, status=status.HTTP_400_BAD_REQUEST)
        
        # 尝试更新或创建员工档案
        employee_profile, created = CompanyEmployeeProfile.objects.update_or_create(
            user_id=user.user_id,
            defaults={
                'company_id': company_id,
                'name': data.get('name'),
                'gender': data.get('gender'),
                'id_card': data.get('id_card'),
                'employee_no': data.get('employee_no'),
                'department': data.get('department'),
                'position': data.get('position'),
                'is_legal_representative': data.get('is_legal_representative', False),
                'is_department_manager': data.get('is_department_manager', False)
            }
        )
        
        response_message = '创建企业员工信息成功' if created else '更新企业员工信息成功'
        
        return Response({
            'code': 200,
            'message': response_message,
            'data': {
                'profile_id': employee_profile.profile_id,
                'company_id': employee_profile.company_id,
                'company_name': company.company_name
            }
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'更新企业员工信息失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def company_employee_list(request):
    """
    获取公司员工列表（仅对公司管理员/部门经理开放）
    """
    try:
        user = request.user
        
        # 验证用户权限（必须是公司法人代表或部门经理）
        try:
            user_profile = CompanyEmployeeProfile.objects.get(user_id=user.user_id)
            if not user_profile.is_legal_representative and not user_profile.is_department_manager:
                return Response({
                    'code': 403,
                    'message': '没有权限访问公司员工列表'
                }, status=status.HTTP_403_FORBIDDEN)
            
            company_id = user_profile.company_id
            
        except CompanyEmployeeProfile.DoesNotExist:
            return Response({
                'code': 403,
                'message': '您不是企业员工，无法访问公司员工列表'
            }, status=status.HTTP_403_FORBIDDEN)
        
        # 获取分页和筛选参数
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('pageSize', 10))
        name_filter = request.query_params.get('name', '')
        department_filter = request.query_params.get('department', '')
        
        # 构建查询条件
        filter_params = {'company_id': company_id}
        if name_filter:
            filter_params['name__icontains'] = name_filter
        if department_filter:
            filter_params['department__icontains'] = department_filter
        
        # 查询数据库
        employees = CompanyEmployeeProfile.objects.filter(**filter_params)
        
        # 计算总数
        total = employees.count()
        
        # 分页
        start = (page - 1) * page_size
        end = start + page_size
        employees_paged = employees[start:end]
        
        # 构建响应数据
        employee_list = []
        for emp in employees_paged:
            employee_data = {
                'profile_id': emp.profile_id,
                'user_id': emp.user_id,
                'name': emp.name,
                'gender': emp.gender,
                'employee_no': emp.employee_no,
                'department': emp.department,
                'position': emp.position,
                'is_legal_representative': emp.is_legal_representative,
                'is_department_manager': emp.is_department_manager
            }
            
            # 获取用户基本信息（如手机号、邮箱）
            try:
                user = User.objects.get(user_id=emp.user_id)
                employee_data['phone'] = user.phone
                employee_data['email'] = user.email
            except User.DoesNotExist:
                pass
            
            employee_list.append(employee_data)
        
        return Response({
            'code': 200,
            'data': {
                'list': employee_list,
                'total': total,
                'page': page,
                'pageSize': page_size
            }
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取公司员工列表失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

